package org.loofer.uiframework;

import android.annotation.TargetApi;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import org.loofer.ext.utils.SdkVersionUtils;
import org.loofer.uiframework.navigator.backstack.AbstractActivity;
import org.loofer.uikit.LayoutInflaterProvider;

public abstract class BaseActivity extends AbstractActivity implements LayoutInflaterProvider {
    private View mBusinessView;

    protected void addFragment(int containerViewId, Fragment fragment) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.add(containerViewId, fragment);
        fragmentTransaction.commit();
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityManager.instance().onCreate(this);
    }

    protected void setBusinessView(View businessView) {
        this.mBusinessView = businessView;
    }

    protected void onResume() {
        super.onResume();
        ActivityManager.instance().onResume(this);
    }

    protected void onPause() {
        super.onPause();
        ActivityManager.instance().onPause(this);
    }

    protected void setFullscreen(boolean fullscreen) {
        Window window = getWindow();
        LayoutParams winParams = window.getAttributes();
        if (fullscreen) {
            winParams.flags |= 1024;
        } else {
            winParams.flags &= -1025;
        }
        window.setAttributes(winParams);
    }

    public LayoutInflater requestLayoutInflater() {
        return getLayoutInflater();
    }

    protected void onDestroy() {
        super.onDestroy();
        ActivityManager.instance().onDestroy(this);
        setViewBackgroundDrawable(this.mBusinessView != null ? this.mBusinessView : getWindow().getDecorView(), null);
        this.mBusinessView = null;
    }

    public void setBackgroundDrawable(Drawable drawable) {
        setViewBackgroundDrawable(this.mBusinessView != null ? this.mBusinessView : getWindow().getDecorView(), drawable);
    }

    @TargetApi(16)
    private void setViewBackgroundDrawable(View view, Drawable drawable) {
        if (view == null) {
            return;
        }
        if (SdkVersionUtils.hasJellyBean()) {
            view.setBackground(drawable);
        } else {
            view.setBackgroundDrawable(drawable);
        }
    }

    public void finish() {
        super.finish();
        overridePendingTransition(0, getExitAnimation());
    }

    protected int getExitAnimation() {
        return R.anim.page_slide_out_right;
    }
}
